layui.use(['form', 'laydate'], function() {
    var form = layui.form
        ,laydate = layui.laydate
        , $ = layui.$;
    //执行一个laydate实例
    laydate.render({
        elem: '#createTime' //指定元素
        ,value: new Date()
    });
    setSelect('/Class/user/getTutorOption', 'user');
    setSelect('/Class/class/getClassOption', 'class');
    setSelect('/Class/course/getCourseOption', 'course');
    //联动下拉框
    form.on('select(class)', function(data){
        if(data != null){
            setSelect('/Class/room/getRoomOption', 'room', data.value);
        }
    })
    //新增 提交表单
    form.on('submit(submit)', function(data){
        $.ajax({
            type: 'post',
            url: '/Class/table/add',
            dataType: 'json',
            data: {
                "userId": data.field.user,
                "classId": data.field.class,
                "roomId": data.field.room,
                "courseId": data.field.course,
                "createTime": data.field.createTime,
                "timeSlot": data.field.timeSlot
            },
            success: (res) =>{
                util.closeLayer($, res);
            }
        })
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
})
//下拉框
function setSelect(url, str, data) {
    let $ = layui.$;
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: { "classId": str === 'room' ? data : null},
        success: (res) =>{
            if (res.code === 0){
                let data = eval(res.data);
                for (let i = 0; i < data.length; i++) {
                    switch (str) { //根据不同数据添加下拉框
                        case 'user': $("#" + str).append("<option value=\"" + data[i].id + "\">" + data[i].realName + "</option>");break;
                        case 'class': $("#" + str).append("<option value=\"" + data[i].id + "\">" + data[i].classCode + "</option>");break;
                        case 'room': $("#" + str).append("<option value=\"" + data[i].id + "\">" + data[i].roomCode + "</option>");break;
                        case 'course': $("#" + str).append("<option value=\"" + data[i].id + "\">" + data[i].courseName + "</option>");break;
                        default :break;
                    }
                }
                //重新渲染
                layui.form.render("select");
            }else layer.msg('数据加载失败');
        }
    })
}